﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Security.Principal;
using System.Xml.Linq;
using COM.Data;

namespace COM.Service
{
    public interface IRolePermissionDataService : ICacheServiceBase
    {
        bool HasPermission(string roleName, string permissionItem);
        IRolePermissionDataService AddRolePermission(string roleName, List<string> permissionList);
        IRolePermissionDataService AddRolePermission<T>(List<string> permissionList) where T : PermissionRole;
    }

    public class RolePermissionDataService : IRolePermissionDataService
    {
        private IPermissionRoleListService permissionRoleListService;
        public RolePermissionDataService(IPermissionRoleListService permissionRoleListService)
        {
            this.permissionRoleListService = permissionRoleListService;
        }

        private Dictionary<string, List<string>> rolePermissionItemList;
        private Dictionary<string, List<string>> RolePermissionItemList
        {
            get
            {
                if(this.rolePermissionItemList == null)
                {
                    this.rolePermissionItemList = new Dictionary<string, List<string>>();
                    if (this.EventReload != null)
                        this.EventReload(this, EventArgs.Empty);
                }
                return this.rolePermissionItemList;
            }
        }
        public bool HasPermission(string roleName,string permissionItem)
        {
            if (this.RolePermissionItemList.ContainsKey(roleName))
                if (this.RolePermissionItemList[roleName].Contains(permissionItem, StringComparer.OrdinalIgnoreCase))
                    return true;
            return false;
        }

        public IRolePermissionDataService AddRolePermission<T>(List<string> permissionList) where T : PermissionRole
        {
            return this.AddRolePermission(this.permissionRoleListService.GetRoleNameByType<T>(), permissionList);
        }

        public IRolePermissionDataService AddRolePermission(string roleName, List<string> permissionList)
        {
            if (!this.RolePermissionItemList.ContainsKey(roleName))
                this.RolePermissionItemList.Add(roleName, new List<string>());
            this.RolePermissionItemList[roleName].AddRange(permissionList);
            return this;
        }

        public void Reload()
        {
            this.rolePermissionItemList = null;
        }


        public event EventHandler EventReload;

    }

}


